import { file } from '@/tmui/components/tm-upload/upload';
import { fetchConfig, fetchConfigMethod } from '@/tmui/tool/lib/interface';
import { fetchNet } from './../tmui/tool/lib/fetch';
import {reactive,ref} from "vue"
// 不需要授权token的api
// wxlogin
const noAuthApi: string[] = []

const rq = async (url: string, data: any = {}, method: fetchConfigMethod = "POST",showAlert = false): Promise<any> => {
    let token: string = uni.getStorageSync('token') || "";
    if(!token){
        try {
           let codeData  = await uni.login({provider:'weixin'})
           if(codeData?.errMsg == "login:ok"){
                let rqdata = await fetchNet.post(uni.hostUrl+"/client/auth/wxcode",{code:codeData.code})
                if(rqdata?.data&&rqdata?.data?.data){
                   let tokens = rqdata?.data?.data;
                    uni.setStorageSync("token",tokens);
                    token = tokens;
                }
           }
        } catch (error) {
            
        }
    }

    

    if(!token){
        uni.hideLoading()
        uni.showModal({
            title:"异常",
            content:"请点击确认重新载入小程序到首页。",
            showCancel:false,
            confirmText:"重新载入",
            success() {
                uni.reLaunch({
                    url:"/pages/index/index"
                })
            },
        })
        return Promise.reject("授权异常")
    }
    return new Promise((resolve, reject) => {
        fetchNet.request({
            method: method,
            data: data,
            header: {
                token: token
            },
            url: uni.hostUrl + url
        }, (config: any) => {
            if (typeof config === 'undefined') return Promise.resolve(true)
            let list = noAuthApi.filter(el => el == url)
            if (list.length > 0) return Promise.resolve(true);
            return Promise.resolve((config.header?.token ?? false))
        }, (res: any) => {
            return Promise.resolve({})
        }).then((res: any) => {
            uni.hideLoading()
            let resData: MyApp.reponseData | any = res?.data;
            if (typeof resData != 'object') {
                uni.showToast({ title: "返回格式有误", icon: "none", mask: true })
				setTimeout(function() {
					reject("返回格式有误")
				}, 1200);
                return;
            }
            let codeStatus = resData?.code ?? -1
            if (codeStatus == -1) {
                uni.removeStorageSync("token")
                uni.showToast({ title: resData.msg, icon: "none", mask: true })
                reject(resData.msg)
                uni.navigateTo({
                    url:'/pages/user/yonghurenzheng'
                })
                
                return;
            }
            if (codeStatus != 0) {
                let msg = resData?.msg ?? "访问有误";
                uni.showToast({ title: msg, icon: "error", mask: true })
                setTimeout(function() {
					reject(msg)
				}, 1200);
                return;
            }

            if(showAlert){
                let msg = resData?.msg ?? "访问有误";
                uni.showToast({ title: msg, icon: "none", mask: true })
                setTimeout(function() {
					resolve(resData)
				}, 1200);
            }else{
                resolve(resData)
            }
        }).catch(error => {
            uni.hideLoading()
            uni.showToast({ title: "网络错误", icon: "none", mask: true })
            setTimeout(function() {
            	reject(error)
            }, 1200);
        })
    })
}

export function useReqList() {
	const first = ref(true)
	/**新闻资讯列表用 */
	const banner = ref<any>([])
    /**新闻资讯列表用 */
	const category = ref<{[key:string]:any}[]>([])

    // 找成果，列表使用。
    const select_data = ref([])

	const status = reactive({
		isError: false,
		isLoading: true,
		isMore: true,
		page: 1,
		page_size: 16,
		keyWord: "",
		count: 0,
		total_page: 0
	})


	const list = ref<unknown[]>([])
	const setOptions = (opstions : { page ?: number, page_size ?: number, keyWord ?: string }) => {
		status.page = opstions?.page ?? status.page;
		status.page_size = opstions?.page_size ?? status.page_size;
		status.keyWord = opstions?.keyWord ?? status.keyWord;
	}
	const resetReq = (clearWord : boolean = true) => {
		status.isError = false;
		status.isLoading = false;
		status.isMore = true;
		list.value = [];
		status.page = 1;
		status.count = 0;
		status.count = 0;
		status.page_size = status.page_size;
		status.keyWord = clearWord ? "" : status.keyWord;
	}

	const actionHttp = async (url : string, custData : any = {},METHOD:fetchConfigMethod  = "POST") => {
		if (!first.value) {
			if (status.isLoading || !status.isMore) return;
		}
		first.value = false;
		status.isLoading = true;
		status.isError = false;
		status.isMore = true;

		return new Promise(async (res, rej) => {
			rq(url, {
				...{
					page: status.page,
					page_size: status.page_size,
					keyword: status.keyWord
				}, ...custData
			},METHOD)
				.then((req) => {
					let data = req as MyApp.ReposeDataListType;
                    
					status.count = data.data.count;
					// status.total_page = data.data.pages;
					banner.value = data.data?.banner ?? [];
					category.value = data.data?.category ?? [];
                  
					select_data.value = data.data?.select_data ?? [];
                    
					if (data.data.list.length < status.page_size) {
						status.isMore = false;
					} else {
						status.page += 1;
					}
					status.isLoading = false;
					list.value.push(...data.data.list)
					res(true)
				})
				.catch(error => {
					uni.hideLoading();
					status.isLoading = false;
					status.isError = true;
					rej(error)
					console.error(error)
				}).finally(() => {
					uni.stopPullDownRefresh();
				})
		})

	}

	return {
		status,
		resetReq,
		actionHttp,
		list,
		setOptions,
		category,
        banner,
        first,
        select_data
	}
}




export const apiUr = {


    wxlogin(code: string): Promise<MyApp.reponseData> {
        return rq("/client/auth/wxcode", { code: code })
    },
    getUserInfo(): Promise<MyApp.reponseData> {
        return rq("/user/info")
    },
    /**首页数据 */
    getSysHomeData(): Promise<MyApp.reponseData> {
        return rq("/sys/index")
    },
	/**新闻或政策首页数据 */
    getNewIndex() {
        return "/news/index"
    },
    /**新闻详情 */
    getNewsDetail(id:string|number): Promise<MyApp.reponseData> {
        return rq("/news/detail",{id})
    },
    /**成果列表数据 */
    achievedIndex() {
        return "/achieved/index"
    },
    /**需求列表数据 */
    demandIndex() {
        return "/demand/index"
    },
    /**服务列表数据 */
    serviceIndex() {
        return "/service/index"
    },
    /**投融资列表数据 */
    financingIndex() {
        return "/financing/index"
    },
    /**团队列表数据 */
    teamIndex() {
        return "/team/index"
    },
    /**数据类型 */
    sysDataType(): Promise<MyApp.reponseData> {
        return rq("/sys/dataType")
    },


    /**成果详情 */
    achievedDetail(id:string|number): Promise<MyApp.reponseData> {
        return rq("/achieved/detail",{id})
    },
    /**需求详情数据 */
    demandDetail(id:string|number): Promise<MyApp.reponseData> {
        return rq("/demand/detail",{id})
    },
    /**服务详情数据 */
    serviceDetail(id:string|number): Promise<MyApp.reponseData> {
        return rq("/service/detail",{id})
    },
    /**投融资详情数据 */
    financingDetail(id:string|number): Promise<MyApp.reponseData> {
        return rq("/financing/detail",{id})
    },
    /**团队详情数据 */
    teamDetail(id:string|number): Promise<MyApp.reponseData> {
        return rq("/team/detail",{id})
    },
    /**详情页的咨询列表 */
    detailCommentList() {
        return "/content/detailCommentList"
    },
    collectDetail(id:string|number,type:string): Promise<MyApp.reponseData> {
        return rq("/content/collect",{id,type},"POST",true)
    },
    contentAddComment(arg:any): Promise<MyApp.reponseData> {
        return rq("/content/addComment",arg,"POST",true)
    },
    contentAdd(arg:any): Promise<MyApp.reponseData> {
        return rq("/content/add",arg,"POST",true)
    },
    
    contentGetCommentDetail(arg:any): Promise<MyApp.reponseData> {
        return rq("/content/detail",arg)
    },
    
    getUserAuthInfo(): Promise<MyApp.reponseData> {
        return rq("/user/authInfo")
    },
    submitAuth(arg:any): Promise<MyApp.reponseData> {
        return rq("/user/auth",arg,"POST",true)
    },
    /**收藏列表 */
    contentList() {
        return "/content/collectList"
    },
    /**收到的咨询列表 */
    getZhiXuncommentList() {
        return "/content/commentList"
    },
    /**获取条件数据 */
    getaddPageData(type:string): Promise<MyApp.reponseData> {
        return rq("/content/addPageData",{type})
    },
    wodefuabu() {
        return "/content/index"
    },
    
    
    
}



